package com.network.retrofit_rx.download;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.network.R;
import com.network.utils.NetworkUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.Locale;

/**
 * 文件下载进度
 * Created by QiQi on 2017/8/23.
 */

public class FileDownLoadProgressDialog extends DialogFragment implements IFileLoadCallback {

    private TextView mCurrentLength,//显示已下载大小
            mTotalLength,//显示总大小
            mPercent;//显示百分比

    private ProgressBar mProgress;//显示下载进度百分比

    private String downLoadUrl;

    protected String sTitle;
    protected String sMsg;
    protected String hint;
    protected DialogInterface.OnCancelListener onCancelListener;
    protected DialogInterface.OnDismissListener onDismissListener;
    private View rootView;
    private String ip;

    private OnDownLoadSuccess onDownLoadSuccess;

    public void setOnDownLoadSuccess(OnDownLoadSuccess onDownLoadSuccess) {
        this.onDownLoadSuccess = onDownLoadSuccess;
    }

    public FileDownLoadProgressDialog setHint(String hint) {
        this.hint = hint;
        return this;
    }

    public FileDownLoadProgressDialog setTitle(String title) {
        this.sTitle = title;
        return this;
    }

    public FileDownLoadProgressDialog setMsg(String msg) {
        this.sMsg = msg;
        return this;
    }

    public void setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) {
        this.onCancelListener = onCancelListener;
    }

    public void setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
        this.onDismissListener = onDismissListener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
            if (rootView == null) {
                rootView = inflater.inflate(getLayout(), container, false);
            }

            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
            initView(rootView);
            return rootView;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData(savedInstanceState);
        initEvent();
    }


    public FileDownLoadProgressDialog setDownLoadUrl(String downLoadUrl) {
        this.downLoadUrl = downLoadUrl;
        return this;
    }

    public FileDownLoadProgressDialog setIp(String ip) {
        this.ip = ip;
        return this;
    }

    protected void initView(View rootView) {
        mCurrentLength = rootView.findViewById(R.id.current_length);
        mTotalLength = rootView.findViewById(R.id.total_length);
        mProgress = rootView.findViewById(R.id.progress);
        mPercent = rootView.findViewById(R.id.percent);
    }

    protected void initData(Bundle savedInstanceState) {
        mProgress.setMax(100);
        setCancelable(false);
    }

    protected void initEvent() {
        DownLoadUtil.getInstance().onAttach(this);
        DownLoadUtil.getInstance().startDownLoadService(getContext(), downLoadUrl, ip);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DownLoadUtil.getInstance().onDetach();
    }

    protected int getLayout() {
        return R.layout.dialog_progress_layout;
    }

    @Override
    public void onSuccess(File file) {
        dismiss();
        if (onDownLoadSuccess != null) {
            onDownLoadSuccess.onSuccess(file);
        }
    }


    @Override
    public void onFailure(Throwable t) {
        dismiss();
        Toast.makeText(NetworkUtils.appContext, "文件下载失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProgress(long progress, long total) {
        String currentSize = getFormatSize(progress);
        if ("0.0M".equals(mTotalLength.getText())) {
            String totalSize = getFormatSize(total);
            mTotalLength.setText(totalSize);
        }
        mCurrentLength.setText(currentSize);

        int percent = (int) (progress * 100L / total);
        mProgress.setProgress(percent);
        mPercent.setText(String.format(Locale.ROOT, "%d%%", percent));
    }


    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    public String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    public interface OnDownLoadSuccess {
        void onSuccess(File file);
    }
}
